<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\User;
use app\admin\model\ShopOrder;
use app\admin\model\Configuration;
use app\admin\model\OrderLog;
use app\admin\model\UserFraze;
use app\admin\model\ChatMessage;
use app\admin\model\Follow;
use app\admin\model\SearchHistory;
use app\admin\model\Product;
use app\admin\model\ProductWish;
use app\admin\model\ProductMessage;
use app\admin\model\ConfigData;
use app\admin\model\Article;
use app\admin\model\ProductViewLog;
use app\admin\model\UserRoseLog;
use app\admin\model\UserOrder;
use app\admin\model\Slideshow;
use app\admin\model\SArea;
use getui\GeTui;
use function PHPSTORM_META\map;
use think\Db;
use think\Exception;

/**
 * 订单控制器
 */
class Order extends Api
{
	protected $noNeedLogin = [];

	public function _initialize(){
		$action = request()->action();
	
		if(!in_array($action,$this->noNeedLogin)){
			$ignore = array('host','accept','content-length','content-type');
			$headers = array();
			if($this->request->request('token')){
				$headers['token'] = $this->request->request('token');
			}else{
				foreach($_SERVER as $key=>$value){
					if(substr($key, 0, 5)==='HTTP_'){
						$key = substr($key, 5);
						$key = str_replace('_', ' ', $key);
						$key = str_replace(' ', '-', $key);
						$key = strtolower($key);
						if(!in_array($key, $ignore)){
							$headers[$key] = $value;
						}
					}
				}
			}
			$token=$headers['token'];
			if(strlen($token)!=32){
				$this->error('请登录');
			}
			$this->user=User::where(array('token'=>$token))->find();
			if(!$this->user){
				$this->error('请登录');
			}
			User::where(array('id'=>$this->user['id']))->update(array('active_time'=>time()));
		}
	}

	//下单操作
	public function place_order(){
		$order_id = $this->request->request('order_id','');
		$order=UserOrder::where(array('order_id'=>$order_id,'status'=>2))->find();
		if(!$order){
			$this->error('参数错误');
		}
		UserOrder::where(['id'=>$order['id']])->update(['status'=>6]);
		$this->success('下单成功');
	} 

	//订单详情
	public function user_order_detail(){
		$id=$this->request->require('order_id');
		$order=UserOrder::where(array('id'=>$id))->find();
		if($order['ship_type']==1 && $order['shipping_fee']==1){
		    $order['order_tips']=ConfigData::where(array('name'=>'shop_1_1'))->getField('value');
		}else{
		    $order['order_tips']='';
		}
		$order['add_time']=date("Y-m-d H:i:s",$order['add_time']);
		$order['product']=Product::where(array('id'=>$order['product_id']))->find();	
		$this->success('获取成功',$order);
	}

    //变更订单状态
    public function setOrderStatus(){
        $id=$this->request->request('id','');
        $status=$this->request->request('status','');
        $where = [
            'id'=>$id
        ];
        $where['user_id'] = $this->user['id'];
        $order = ShopOrder::where($where)->find();
        if(!$order){
            $this->error('参数错误');
        }
		$update = ['status'=>$status];
		Db::startTrans();
		try {
			if($status == -1){ //取消订单操作
				ShopOrder::where(['id'=>$order['id']])->update($update);
				Db::commit();
				$this->success('操作成功');
			}
			Db::commit();
			$this->error('操作失败');
		} catch (Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
    }

	//更新评价状态
	public function evaluate(){
		$order_id = $this->request->request('order_id');
		$commentId = $this->request->request('commentId');
		$res = UserOrder::where('id',$order_id)->update(['commentId'=>$commentId]);
		if($res){
			$this->success('操作成功');
		}else{
			$this->error('操作失败');
		}
	}

	//催发货
	public function expedite(){
		$id = $this->request->request('id','');
		$order = UserOrder::where(['id'=>$id,'user_id'=>$this->user['id']])->find();
		if(!$order){
			$this->error('参数错误');
		}
		//判断当天是否已经催发货一次  如果已经催过则第二天才能再催
		$redis = redis_init();
		$name = $order['user_id'].$order['id'];
        $info = $redis->get($name);
        if($info){
			//判断时间
			$time1 = date('Y-m-d',$info);
			$time2 = date('Y-m-d',time());
			if($time1 == $time2){
				$this->error('每天只能催发货一次哦');
			}
        }
		$redis->set($name,time());

		//官方客服发送给卖方一条私信
		$arr = [
			'content' => '你有一笔待发货订单，请及时预约快递发货。',
			'user_id' => 439,
			'js_user_id'=> $order['shop_id'],
			'product_id'=>$order['product_id'],
			'add_time'=>time(),
		];
		$arr['sort'] = $arr['js_user_id'].'0'.$order['product_id'].$arr['user_id'];
		ChatMessage::insert($arr);
		$data = [
			"character_string1"=>["value"=>$order['order_id']],
			"thing2"=>[ "value"=> '你有一笔待发货订单，请及时预约快递发货。'], 
			"time4"=>["value"=>date('Y-m-d H:i:s',$order['add_time']) ]
		];
		send_subscription($order['shop_id'],'Ij7RyEc_gcTHbbKkANbp1UZzo2q3q3alO_CPuth2jMc','/pages/user/sellOrder',$data);
		$this->success('操作成功');
	}


	//已发货订单，72小时候自动确认收货
    public function auto_recieve(){
        $time=time()-3600*24*3;
        
        //自提
        $where = ['ship_type'=>2,'status'=>['in','2,3'],'add_time'=>['<',$time]];
        //买家付邮
        $where1 = ['ship_type'=>1,'status'=>3,'delivery_time'=>['<',$time]];

        $orders=UserOrder::where($where)
        ->whereOr(function($query) use ($where1){
            $query->where($where1);
        })->select();
        if($orders){
            foreach($orders as $a=>$b){
                UserOrder::where(array('id'=>$b['id']))->update(array('status'=>5,'recieve_time'=>time()));
                $product=Product::where(array('id'=>$b['product_id']))->find();
                if($product){
                    //首次订单完成给奖励
                    $redis = redis_init();
                    $name = 'add_score_25_'.$product['user_id'];
                    $info = $redis->get($name);
                    if(!$info){
                        //未获取过奖励则直接给奖励
                        roseandlog($product['user_id'],3,25,'首次订单完成');
                        $redis->set($name,time());
                    }

                    roseandlog($product['user_id'],$b['total_money'],6,'售出商品获得');
                    ProductMessage::insert(array('product_id'=>$b['product_id'],'message_id'=>0,'title'=>'自动确认收货，交易商品:【'.$product['title'].'】','user_id'=>$b['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                }
            }
        }

        exit('order to complete over');
    }
    // //已发货订单，72小时候自动确认收货
    // public function auto_recieve(){
    //     $id=$this->request->request('id','');
    //     $order = UserOrder::where(array('status'=>['in','1,2,3'],'id'=>$id,'user_id'=>$this->user['id']))->find();
    //     //redis锁定该订单  避免多次确认收货
    //     $redis = redis_init();
    //     $is_sd = $redis->get($id.'_'.$this->user['id']);
    //     if($order &&  !$is_sd){
    //         UserOrder::where(array('id'=>$order['id']))->update(array('status'=>5,'recieve_time'=>time()));
    //         $product=Product::where(array('id'=>$order['product_id']))->find();
    //         if($product){
    //             roseandlog($product['user_id'],$order['total_money'],6,'售出商品获得');
    //             ProductMessage::insert(array('product_id'=>$order['product_id'],'message_id'=>0,'title'=>'自动确认收货，交易商品:【'.$product['title'].'】','user_id'=>$order['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
    //             $redis->set($id.'_'.$this->user['id'],'');
    //         }
    //     }
    // }

	//未支付订单自动取消
    public function no_payment(){
        $time=time()-900;
        //未支付订单
        $where = ['status'=>1,'add_time'=>['<',$time],'ship_type'=>1];
        $orders=UserOrder::where($where)->select();
 
        if($orders){
            foreach($orders as $a=>$b){
                UserOrder::where(array('id'=>$b['id']))->update(array('status'=>-1));
                Product::where(array('id'=>$b['product_id']))->update(array('is_sale'=>0));
            }
        }
        exit('order to complete over');
    }


    //获取我的订单列表
    public function user_order(){
		$status=$this->request->request('status','');  //1 我买的   2我卖的
		$page=$this->request->request('page',1);
		$pagesize=$this->request->request('pagesize',10);
		$where=['a.user_id'=>$this->user['id']];
		if(isset($status) && $status != ''){
            $where['a.status'] = $status;
        }
		$list=ShopOrder::alias('a')
		->order("add_time desc")
		->field("a.*,s.name as shop_name,u.nickname,u.mobile,u.avatar")
		->where($where)
		->join("shop s","s.id = a.shop_id")
		->join("user u","u.id = a.user_id")
		->limit(($page-1)*$pagesize,$pagesize)
		->select();
		foreach($list as &$v){
			if($v['status'] == 0 && time()-$v['add_time'] > 900){
				//超过15分钟自动取消订单
				$v['status'] = -1;
				ShopOrder::where(['id'=>$v['id']])->update(['status'=>-1]);
			}
			$b['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
		}
        $this->success('获取成功',$list);
	}

	//更新商品地址
	public function updateAddress(){
		$data = [];
		$data['address']		= $this->request->request('address','');
		$data['province']		= $this->request->request('province','');
		$data['city']			= $this->request->request('city','');
		$data['area']			= $this->request->request('area','');
		$data['name']           = $this->request->request('name');
		$data['phone']          = $this->request->request('phone');
		$id = $this->request->request('id');
		$res = Product::where('id',$id)->update($data);
		if($res){
			$this->success('操作成功');
		}else{
			$this->error('更新寄件地址失败');
		}

	}

	//计算运费
	public function get_freight(){
		$address = $this->request->request('address','');
		$address_tow = $this->request->request('address_tow','');
		$weight = $this->request->request('weight','');
		$arr = [
			[
				'address'=>10,
				'address_tow'=>12,
			],
			[
				'address'=>11,
				'address_tow'=>15,
			],
			[
				'address'=>13,
				'address_tow'=>16,
			],
			[
				'address'=>14,
				'address_tow'=>20,
			],
			[
				'address'=>15,
				'address_tow'=>25,
			],
		];
		if($weight == '1kg'){
			$i = 0;
		}elseif($weight == '2kg'){
			$i = 1;
		}elseif($weight == '3kg'){
			$i = 2;
		}elseif($weight == '4kg'){
			$i = 3;
		}elseif($weight == '5kg'){
			$i = 4;
		}
		//同城
		if($address == $address_tow){
			$m = 'address';
		}else{
			$m = 'address_tow';
		}
		$this->success('操作成功',$arr[$i][$m]);
		
		
	}

    //生成订单
	public function order_submit(){
	    $order_id=date("YmdHis").rand(1000,9999);
		$data['order_id']=$order_id;
		$data['product_id']=$this->request->request('product_id');
		
		$fraze=UserFraze::where(array('user_id'=>$this->user['id'],'module_id'=>3))->find();
		if($fraze){
            $this->error('您的账号已被限制【兑换宝贝功能】了,解封请联系在线客服');
		}
		if(empty($data['product_id'])){
            $this->error('商品id丢失');
		}
		$product=Product::where(array('id'=>$data['product_id']))->find();
		if($product['is_sale']==1){
            $this->error('此商品已经售出了');
		}
		if($product['user_id']==$this->user['id']){
            $this->error('无法兑换自己的物品!');
		}
        if($product['peisong']=='1,0'){//自提
    		$data['ship_type']=2;
        }else{
    		$data['ship_type']=1;
			//买家付邮提示用户前往小程序进行付款
			$this->error('请去余享小程序完成下单!');
        }
        $data['shipping_fee']=$product['shipping_fee'];
		$data['user_id']=$this->user['id'];
		$data['status']	=0;
		if($product['price']>$this->user['rose_money']){
            $this->error('余额不足，兑换失败');
		}
		$data['price']=$product['price'];
		$data['quantity']=1;
		$data['total_money']=$product['price'];
		
		$address_id=$this->request->request('address_id');
		$address_id=str_replace('undefined','',$address_id);

		$data['mark']=$this->request->request('mark');
        $data['status']=2;
		$data['add_time']=time();
		
		$repeat=UserOrder::where(array('product_id'=>$data['product_id'],'user_id'=>$data['user_id'],'status'=>1))->find();
		if($repeat){
            $this->error('您已经提交过订单了');
		}
		$oid	=	UserOrder::insert($data);
		if($oid){
			$this->sendOrderSuccess($data,$product);
            $this->success('订单生成成功',$order_id);
		}else{
            $this->error('订单创建失败');
		}
	}


	//下单成功后操作
	public function sendOrderSuccess($data,$product){
		//  下单后标为售出
		Product::where(array('id'=>$data['product_id']))->update(array('is_sale'=>1));
		roseandlog($this->user['id'],0-$data['total_money'],5,'兑换商品扣除');
		ProductMessage::insert(array('product_id'=>$data['product_id'],'message_id'=>0,'title'=>'买家'.$this->user['nickname'].'下单了，请尽快发货:【'.$product['title'].'】','user_id'=>$data['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));

		


		$configuration=Configuration::where(array('id'=>1))->find();
		// 注意使用GMT时间  
		date_default_timezone_set("GMT");  
		$target = "https://dysmsapi.aliyuncs.com/?";  
		$dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601规范  
		$accessKeyId = $configuration['access_key'];      // 这里填写您的Access Key ID  
		$accessKeySecret = $configuration['access_secret'];  // 这里填写您的Access Key Secret  
		$ParamString="{}";
		$mobile=$product['phone'];
		$data = array(  
			'AccessKeyId' => $accessKeyId,
			'Action' => 'SendSms',
			'Format' => 'XML', 
			'OutId' => '123',
			'PhoneNumbers' => $mobile,
			'RegionId' => 'cn-hangzhou',
			'SignName'=>$configuration['sign_name'],
			'SignatureMethod' => 'HMAC-SHA1',
			'SignatureNonce'=> '45e25e9b-0a6f-4070-8c85-'.uniqid(),
			'SignatureVersion' => '1.0',
			'TemplateCode' => 'SMS_274540075', 
			'TemplateParam' => $ParamString,
			'Timestamp' => date("Y-m-d H:i:s"), 
			'Version' => '2017-05-25'
		);  
		$data['Signature'] = computeSignature($data, $accessKeySecret);  
		// 发送请求  
		$result = xml_to_array(https_request($target.http_build_query($data)));
		//print_r($result);
		if(!empty($result['Error']['Message'])){
			$this->error($result['Error']['Message']);
		}
		if($product['notice'] == 0){
			return true;
		}
		//发送订阅消息
		$data = [
			"thing8"=>["value"=>$product['title']],
			"thing3"=>[ "value"=> '待发货'], 
			"thing4"=>["value"=>'你的闲置已赠出，请去订单页联系买家自提！' ]
		];
		send_subscription($product['user_id'],'UJnRdmFH3FHRqisFtbKCuYJRxHEK1J8sJydn0DToLFg','/pages/user/sellOrder',$data);
	}
	//订单发货订阅
	public function order_notice(){
		$order_id= $this->request->request('order_id',0);
		$notice= $this->request->request('notice',0);
		if($order_id && $notice==1){
			UserOrder::where(array('order_id'=>$order_id))->update(array('notice'=>1));
		}elseif($order_id && $notice==0){
			UserOrder::where(array('order_id'=>$order_id))->update(array('notice'=>0));
		}
		$this->success('操作成功');
	} 

	//下单订阅
	public function product_notice(){
		$product_id= $this->request->request('product_id',0);
		$notice= $this->request->request('notice',0);
		if($product_id && $notice==1){
			Product::where(array('id'=>$product_id))->update(array('notice'=>1));
		}elseif($product_id && $notice==0){
			Product::where(array('id'=>$product_id))->update(array('notice'=>0));
		}
		$this->success('操作成功');
	}
}